<template>
<div class="order_list_div" style="position: absolute;width: 100%">
	
	<!-- <my-header :title="'意见反馈'" :hasTitle="true"  :hasBack="true" :IDGModel="true" :IDGInputSelector="['#feedbackSend','#feedbackPhone','#feedbackEmail']"></my-header> -->
	
	
	<div class="feedback" style="text-align:left;" id="feedbackBox">
        <div id="feedbackContent">
            <p>选择类型</p>
            <div class="standard_con">
                <li :class="num == index ? 'active' : ''" v-for="(item, index) in data" :key="index" @click="num = index; categoryName = item.categoryName" >{{item.categoryName}}<i class="icon njfont nj-xuanzhong"></i></li>
            </div>
            <p>描述</p>
            <div class="feedback_text">
                <textarea placeholder="输入意见建议详情，帮助我们更好的理解您的心声" style="overflow-y:auto;" v-model="describle" maxlength="500" id="feedbackSend"></textarea>
                <em id="counter">{{nowLength}}/500</em>
            </div>
            <!--<div class="feedback_text">
                <textarea placeholder="输入意见建议详情，帮助我们更好的理解您的心声" v-model="describle" maxlength="500"></textarea>
                <em id="counter">{{nowLength}}/500</em>
            </div>-->
            <p class="aui-margin-b-15">联系方式（建议您至少留下一个联系方式）</p>
            <ul class="aui-list aui-form-list aui-margin-b-15">
                <li class="aui-list-item">
                    <div class="aui-list-item-inner">
                        <div class="aui-list-item-label">联系方式</div>
                        <div class="aui-list-item-input">
                            <input type="number" placeholder="请输入手机号码" ref="userPhone" id="feedbackPhone" v-model="phone">
                        </div>
                    </div>
                </li>
                <li class="aui-list-item">
                    <div class="aui-list-item-inner">
                        <div class="aui-list-item-label">电子邮箱</div>
                        <div class="aui-list-item-input">
                            <input type="text" placeholder="请输入邮箱地址" id="feedbackEmail" ref="userEmail" v-model="mail"/>
                        </div>
                    </div>
                </li>
            </ul>
        </div>
	
        <div class="aui-content-padded">
            <div class="aui-btn aui-btn-danger aui-btn-block" @click="submit">提交</div>
        </div>
	</div>
</div>
</template>

<script>
//	:IDGModel="true" :IDGInputSelector="['#afterSaleOederNode']"
	// import MyHeader from "../../../containers/header";
	import { Toast } from '../../../utils/toast.js';
    import {mapMutations, mapActions, mapGetters} from "vuex";
    import { getHrefParams } from '../../../utils/zx';
    import { CHANGE_NAVIGATION } from '../../../config/postMessage-types'; 

    import axios from 'axios';
    
//	import {reFreshUserInfo} from '../../../utils/WXH/login.js';
	export default {
		data() {
			return {
				data: null,
				num: 0,
				phone: null,
				describle: null,
				mail: null,
				categoryName: null,
                nowLength:500,
                disableFlag:false,
                // sessionId:null
			}
		}
        ,
        created(){
            let titleConfig = JSON.stringify({
                type: CHANGE_NAVIGATION,
                params: {
                    title: "意见反馈"
                }
            })
            setTimeout(() => {
                window.postMessage(titleConfig)
            },300)
        },
		mounted() {
			// this.initTextareaFocusEvent();
            this.initData();
            console.log(this.describle,'this.describle')
		}
		,
		computed:{
			...mapGetters('wxh', [
				'sessionId',
				'login'
			]),
			...mapGetters('zx', [
				'getFeedBackInfo'
			])
			
		}
		,
		watch:{
			describle(newVal,oldVal){
                this.saveInfo();
                // console.log(this.describle.length,'长度') 
				//解决 复制粘贴字数不减少问题 
				if(this.describle && this.describle.length){
                    this.nowLength = 500 - Number(this.describle.length);
                }
                //  解决回车符 maxlength 与 str.length 计算不匹配问题 
                let reg = /(\r\n)|(\n)/g ;
                let arr = this.describle.match(reg); //正则匹配回车 返回匹配到子串的数组
                if(arr && arr.length){
                    this.nowLength = 500 - arr.length - Number(this.describle.length);
                }
				if(this.nowLength < 3){
                     this.nowLength = 0;
                }
                if(this.describle.length === 0){
                    this.nowLength = 500;
                }
			},
			num(newVal,oldVal){
				this.saveInfo();
			},
			phone(newVal,oldVal){
				this.saveInfo();
			},
			mail(newVal,oldVal){
				this.saveInfo();
			}
		},
		components: {
	        // "my-header": MyHeader,
	    }
		,
		methods: {
			...mapMutations('zx', [
				"setFeedBackInfo"
            ]),
            //监听买家留言框的focus事件 开始
	        initTextareaFocusEvent() {
	            this.$refs.userPhone.onfocus = () => {
	                console.log("input框框获取到了焦点");
	                this.initInputStyle();
	            }
	            this.$refs.userPhone.onblur = () => {
	                console.log("失去焦点");
	                //重置样式
	                this.unsetStyle();  
                }
                this.$refs.userPhone.ontouchstart = () => {
                    console.log('touch清除事件')
                    this.unsetStyle();  
                }
                this.$refs.userEmail.onfocus = () => {
	                console.log("input框框获取到了焦点");
	                this.initInputStyle();
	            }
	            this.$refs.userEmail.onblur = () => {
	                console.log("失去焦点");
	                //重置样式
	                this.unsetStyle();  
                }
                this.$refs.userEmail.ontouchstart = () => {
                    console.log('touch清除事件')
                    this.unsetStyle();  
                }
	        },
	        //如果是安卓机,调整页面margin-bottom供用户看到input框
	        initInputStyle() {
	            let isAndroid = navigator.userAgent.indexOf("Android") > -1;
	            if (isAndroid) {

					let box = document.getElementById('feedbackBox');
					let box2 = document.getElementById('feedbackContent');

	                let scrollTopContainer = document.body;

	                box.style.marginBottom = "45vh";
	                box2.scrollTop = 200;
					// console.log(box.scrollTop,'滚动');
					// console.log(box.scrollTop,'滚动');
	                //给一个scrollTop值的变化，自动滑上去
	                let distance = parseInt(getComputedStyle(box, null).marginBottom.slice(0, -2));
	                let duration = 200 / 16.7;
	                let speed = distance / duration;
	                this.scrollAnim = setInterval(() => {
	                    scrollTopContainer.scrollTop += speed;
	                    if (scrollTopContainer.scrollTop >= distance) {
	                    	console.log("/-*****-/");
	                        scrollTopContainer.scrollTop = distance;
	                        clearInterval(this.scrollAnim);
	                    }
	                }, 16.7);
	            }
	        },
	        unsetStyle() {
	            //清除计时器
	            clearInterval(this.scrollAnim);
	            this.scrollAnim = null;
				let box = document.getElementById('feedbackBox');
				let box2 = document.getElementById('feedbackContent');
	            box.style.marginBottom = "unset";
	            box2.scrollTop = 0;
	        },
			//存用户填入信息
			saveInfo(){
				let obj = {
					num:this.num,
					phone:this.phone,
					describle:this.describle,
					mail:this.mail
				};
				this.setFeedBackInfo(obj);
			},
			countChar(spanName){  
				console.log(111)
				if(this.describle && this.describle.length){
				 	console.log(222)
				 	this.nowLength = 500 - Number(this.describle.length);
                }
                //  解决回车符 maxlength 与 str.length 计算不匹配问题 
                let reg = /(\r\n)|(\n)/g ;
                let arr = this.describle.match(reg); //正则匹配回车 返回匹配到子串的数组
                if(arr && arr.length){
                    this.nowLength = this.nowLength - arr.length - Number(this.describle.length);
                }
				//解决 出现字数-1的问题 
				if(this.nowLength < 3){
				 	this.nowLength = 0;
				}
			}, 
			checkUserSave(){
				var obj = this.getFeedBackInfo;
				for(let item in obj){
					if(item){
						return false;
					}
				}
				return true;
			},
			//对接运营接口
			getInitData(){
				let flag = this.checkUserSave();
				var obj = this.getFeedBackInfo;
				if(!flag){
//					this.num = obj.num;  // 返回数据后台可控制，暂未从本地获取
					this.phone = obj.phone;
					this.describle = obj.describle;
					this.mail = obj.mail;
				}
	            let config = {
	            	url:window.api.customer_host+"/questionCategoryVue/getListByContentType?contentType=2",
	            	method: 'GET',
	            	headers: {'sessionId': this.sessionId},
                };
                console.log(config,'请求入参')
	             axios(config).then((res)=>{
	             
	             	if(res.returncode == 0) {
						Toast({
						  message: res.msg,
						  type: 'fail',
						  duration: 2000
						});
	
						return
					}
	             	console.log(res.data.data);
	             	this.data = res.data.data;
	             })
			},
			//对接运营接口  提交意见反馈
			submitDate(){
//				/customerAdviceVue/insertQaAdviceFromH5
                console.log('提交开始',this.describle,this.describle.replace(/\$/g,''))
                let describle = this.describle && this.describle.replace(/\$/g,'');
                let phone = this.phone && this.phone.replace(/\$/g,'');
                let mail =  this.mail && this.mail.replace(/\$/g,'')
                console.log(phone,mail,describle,'describle');
				let params = {
                    "categoryId":this.data[this.num].categoryId,
                    "questionDesc":describle,
                    "contractPhone":phone,
                    "contractEmail":mail,
                    "questionImages":""
                }
                console.log('提交开始params',params)
				let config = {
	            	url: window.api.customer_host+'/customerAdviceVue/insertQaAdviceFromH5',
	            	method: 'POST',
	            	data: params,
	            	headers: {'sessionId': this.sessionId, 'Content-Type':'application/json', 'Accept' : 'application/json'},
                }
                console.log(params,'提交意见反馈入參')
				axios(config).then((res)=>{
					console.log(res.data.returnCode,'提交意见反馈');
					if(res.data.returnCode == 0) {
						console.log(res,'提交意见反馈1');
						Toast({
						  message: res.msg,
						  type: 'fail',
						  duration: 2000
						});
						return
					} else if (res.data.returnCode == 1) {
						console.log(res,'提交意见反馈2');
						let obj = {};
						this.setFeedBackInfo(obj);
						Toast({
						  message: "反馈提交成功",
						  type: 'success',
						  duration: 2000
						});
                        // this.$router.push({ path:'server'})	;
                        window.history.back();
					}
				})
			},
			async initData() {
			    //调用個人中心的方法刷新用户信息 防止vuex用户信息失效
				// this.reFreshUserInfo(this);
                //初始化数据
                console.log('进入意见反馈')
				this.getInitData();
			}
			,
			async submit () {
                console.log('校验邮箱')
				let categoryId = this.data[this.num].categoryId;
				if(this.describle == null){
					Toast({
					  message: '类型和描述不能为空',
					  type: 'fail',
					  duration: 2000
					});
                    return
				}
				if(!this.phone && !this.mail){
					Toast({
					  message: '请输入联系方式',
					  type: 'fail',
					  duration: 2000
					});
					return
                }
                
				if(this.phone){
					let reg = new RegExp(/^0?(13[0-9]|15[012356789]|17[0136789]|18[0-9]|14[57]|19[0-9])[0-9]{8}$/)
	                if(!reg.test(parseInt(this.phone))){
	                    Toast({
						  message: '手机格式不正确',
						  type: 'fail',
						  duration: 2000
						});
	                    return
	                }
                }
                
				if(this.mail){
                    var reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/; 
					var flag = reg.test(this.mail);
                    console.log(this.mail,'邮箱校验'); 
                    console.log(flag)
					if(!flag){
						 Toast({
						  message: '邮箱格式不正确',
						  type: 'fail',
						  duration: 2000
						});
	                    return
					}
                }
				this.submitDate();
			},
		}
	}
</script>
<style scoped="scoped">
	.feedback{
		border-top: 0;
	}
	.feedback_text em {
	    position: absolute;
	    right: 0.5rem;
	    bottom: -1rem;
	    color: #9A9A9A;
	}


</style>